package cn.wit.summit.chwan.ui.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.flyco.tablayout.SlidingTabLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.Stat.Event;
import cn.wit.summit.chwan.Stat.StatFactory;
import cn.wit.summit.chwan.adapters.FragmentPagerAdapter;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.CommentAlllistIntentData;
import cn.wit.summit.chwan.models.dto.CommentBaseBean;
import cn.wit.summit.chwan.models.dto.GameInfoDetial;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.dto.GameTagInfoBean;
import cn.wit.summit.chwan.models.dto.JumpBaseBean;
import cn.wit.summit.chwan.models.dto.ResponseSratues;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.event.EnergyEvent;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.MyActivity;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.ui.fragment.CommentAllListFragment;
import cn.wit.summit.chwan.ui.fragment.DetailFragment;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.EasyBlur;
import cn.wit.summit.chwan.utils.FrescoLoadUtil;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.StatusBarUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.SystemBarTintManager;
import cn.wit.summit.chwan.utils.ToastUtils;
import cn.wit.summit.chwan.widgets.FlowLayout;
import cn.wit.summit.chwan.widgets.GameDetialDownButn;
import cn.wit.summit.chwan.widgets.RecommendTopDownloadView;
import cn.wit.summit.chwan.widgets.RecommendTopEnergyView;
import retrofit2.Retrofit;

/**
 * Created by pengsk on 2018/3/29.
 */
public class GameDetailActivity extends MyActivity {
    String gameId;
    @Bind(R.id.appBarLayout)
    AppBarLayout appBarLayout;
    @Bind(R.id.main_content)
    CoordinatorLayout main_content;
    @Bind(R.id.colltoobar)
    CollapsingToolbarLayout colltoobar;
    @Bind(R.id.viewPager)
    ViewPager viewPager;
    @Bind(R.id.tabs)
    SlidingTabLayout tabs;
    //    TabLayout tabs;
    Activity context;

    @Bind(R.id.tips)
    FlowLayout tips;
    @Bind(R.id.topImag)
    ImageView topImag;
    @Bind(R.id.detail_icon)
    SimpleDraweeView detail_icon;
    @Bind(R.id.appName)
    TextView appName;
    @Bind(R.id.tv_autho)
    TextView tv_autho;
    @Bind(R.id.load_version)
    TextView load_version;
    @Bind(R.id.versionInfo)
    TextView versionInfo;
    @Bind(R.id.togetherPlayText)
    TextView togetherPlayText;
    @Bind(R.id.togetherPlayTitle)
    TextView togetherPlayTitle;
    @Bind(R.id.line)
    View line;
    @Bind(R.id.backImag)
    ImageView backImag;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.installButn)
    GameDetialDownButn installButn;
    @Bind(R.id.folowGame)
    ImageView folowGame;
    @Bind(R.id.folowText)
    TextView folowText;
    @Bind(R.id.topBarDownload)
    RecommendTopDownloadView topBarDownload;
    @Bind(R.id.topBarEnergy)
    RecommendTopEnergyView topBarEnergy;
    @Bind(R.id.defalutView)
    LinearLayout defalutView;
    @Bind(R.id.commentEnergy)
    TextView commentEnergy;
    DetialRecvier detialRecvier;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    //tintManager.setStatusBarTintResource(R.color.ov_status_bar);
    class DetialRecvier extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (intent.getAction().equals("gameDetialShowCommentTab"))
                    viewPager.setCurrentItem(1);
                else {
                    String count = intent.getStringExtra("Game_comment_count");
                    if (tabs != null && tabs.getTitleView(1) != null)
                        tabs.getTitleView(1).setText("评论(" + count + ")");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private AnimationDrawable anim;

    public void showLodingLayout() {
//        lodingLayout.setVisibility(View.VISIBLE);
        defalutView.setVisibility(View.VISIBLE);
    }

    public void hideLodingLayout() {
//        lodingLayout.setVisibility(View.GONE);
        defalutView.setVisibility(View.GONE);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        gameId = getIntent().getStringExtra("gameID");
        StatFactory.getInstance().sendGameGameDetial(this,gameId, Event.clickPage);
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatFactory.getInstance().sendGameGameDetial(this,gameId, Event.vistPage);
//        MyApplication.commentAddEnergy = 123;
        if (MyApplication.commentAddEnergy!=0) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    EnergyEvent energyEvent = new EnergyEvent();
                    energyEvent.setNumber(MyApplication.commentAddEnergy);
                    energyEvent.setMustShow(true);
                    EventBus.getDefault().post(energyEvent);
                    MyApplication.commentAddEnergy = 0;
                }
            },300);
        }
        afterView();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.e("gamedetial oncreate");
        setContentView(R.layout.gamedetail_activity);
        ButterKnife.bind(this);
        gameId = getIntent().getStringExtra("gameID");
        StatFactory.getInstance().sendGameGameDetial(this,gameId, Event.clickPage);
//        toolbar.setTitle("");
        topLayout.setVisibility(View.GONE);
        IntentFilter filter = new IntentFilter();
        filter.addAction("gameDetialShowCommentTab");
        filter.addAction("send.broadcast.game.comment.count");
        detialRecvier = new DetialRecvier();
        registerReceiver(detialRecvier, filter);

        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

//        afterView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(detialRecvier);
    }

    private int statubarH;
    SystemBarTintManager tintManager;

    void afterView() {
        context = this;
        LogUtils.e("gamedetial afterview");
        getDetialData();
        showLodingLayout();

        statubarH = getStatusBarHeight(context);
        StatusBarUtil.setSratusMode(this, 0xff7f7f7f, true);
        StatusBarUtil.StatusBarDarkMode(this, StatusBarUtil.StatusBarLightMode(this));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            LogUtils.e("getStateBarHeight():" + getStateBarHeight());
            setTranslucentStatus(true);
            tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(false);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            tintManager.setStatusBarTintResource(R.drawable.header_gradient_bg);// 通知栏所需颜色
        }
        toolbar.getBackground().setAlpha(0);
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                int totalMove = appBarLayout.getHeight() - toolbar.getHeight() - statubarH;
                int hasMove = Math.abs(verticalOffset);
                if (totalMove - statubarH <= hasMove) {
                    toolbar.getBackground().setAlpha(255);
                    return;
                } else if (hasMove <= statubarH) {
                    toolbar.getBackground().setAlpha(0);
                    return;
                }
                if (hasMove > statubarH && (hasMove - statubarH) <= totalMove - statubarH * 2)
                    toolbar.getBackground().setAlpha((hasMove - statubarH) * 255 / (totalMove - statubarH * 2));

            }
        });

        if (topBarDownload != null) {
            topBarDownload.setTotalDownloadNum();
        }
//        setTopBarDownload(topBarDownload, topBarEnergy);
    }

    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    private int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    void getDetialData() {
        LogUtils.e("gamedetial getdata");
        if (NetWorkUtils.isNetworkConnected(context)) {
            try {
                api.getGameDetialData(gameId, AccountUtil.getInstance().getUid()).enqueue(new MyCallback<ResponseBase<GameInfoDetial>>() {
                    @Override
                    public void onSuccess(ResponseBase<GameInfoDetial> model) {
                        GameInfoDetial data = model.getData_info();
                        if (data == null) {
                            hideLodingLayout();
                            return;
                        }
                        updateUi(data);
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        showToast(msg);
                        LogUtils.e("gamedetial getdataError");
                        hideLodingLayout();
                        showFailedLoding(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                topLayout.setVisibility(View.GONE);
                                hideFailedLoding();
                                getDetialData();
                            }
                        });
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                hideLodingLayout();
                LogUtils.e("gamedetial excption");
            }
        } else {
            LogUtils.e("gamedetial nonetwork");
            topLayout.setVisibility(View.VISIBLE);
            showFailedLoding(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    topLayout.setVisibility(View.GONE);
                    hideFailedLoding();
                    getDetialData();
                }
            });
            hideLodingLayout();
            showToast("请检查网络链接是否正常");
        }
    }


    private void folowgame(final String gameId) {
        int uid = AccountUtil.getInstance().getUidNotToLogin(context);
        if (uid == 0) return;

        api.followGame(uid , gameId, AccountUtil.getInstance().getToken()).enqueue(new MyCallback<ResponseBase<ResponseSratues>>() {
            @Override
            public void onSuccess(ResponseBase<ResponseSratues> model) {
                ResponseSratues data = model.getData_info();
                if (data != null) {
                    if (data.isState()) {//收藏成功
                        ToastUtils.getInstance(context).showToastSystem("收藏成功");
                    } else {//已收藏
                        ToastUtils.getInstance(context).showToastSystem("已收藏过");
                    }
                    folowGame.setImageResource(R.mipmap.ic_folowgame_image);
                    folowText.setText("已收藏");
                }
            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
    }

    private GameInfoDetial modleFourBean;
    private DetailFragment detailFragment;

    void updateUi(GameInfoDetial modleFourBean) {
        LogUtils.e("gamedetial updateui");
        this.modleFourBean = modleFourBean;
        if (modleFourBean != null && modleFourBean.getGame_share_ad() != null) {
            togetherPlayTitle.setText(modleFourBean.getGame_share_ad().getJump_title());
            togetherPlayText.setText("¥"+modleFourBean.getGame_share_energy_num());
            commentEnergy.setText("+"+modleFourBean.getGame_comment_energy_num());
            installButn.setEnergyText("+"+modleFourBean.getGame_down_energy_num());
        }

        initView(modleFourBean);
        String blurUrl = modleFourBean.getGame_ico();
        try {
            blurUrl = modleFourBean.getGame_slide_pic().getPic_list().get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        FrescoLoadUtil.getInstance().loadImageBitmap(blurUrl, new FrescoLoadUtil.FrescoBitmapCallback<Bitmap>() {
            @Override
            public void onSuccess(Uri uri, Bitmap result) {
                Bitmap finalBitmap = EasyBlur.with(context)
                        .bitmap(result) //要模糊的图片
                        .radius(10)//模糊半径
                        .scale(4)//指定模糊前缩小的倍数
                        .policy(EasyBlur.BlurPolicy.FAST_BLUR)//使用fastBlur
                        .blur();
                topImag.setImageBitmap(finalBitmap);
            }

            @Override
            public void onFailure(Uri uri, Throwable throwable) {

            }

            @Override
            public void onCancel(Uri uri) {

            }
        });

        List<FragmentPagerAdapter.Item> items = new ArrayList<>();
        CommentAlllistIntentData intentData = new CommentAlllistIntentData();
        intentData.setGameId(modleFourBean.getGame_id());
        intentData.setPackageName(modleFourBean.getGame_package_name());
        intentData.setGameType(modleFourBean.getGame_startup_num() + "");
        intentData.setGameIsStart(1);
        intentData.setSgcSwitch(0);
        intentData.setBespeakSwitch(0);
        intentData.setCommentScoreSwitch("");
        detailFragment = DetailFragment.newInstance(modleFourBean);
        if (!detailFragment.isAdded())
            items.add(new FragmentPagerAdapter.Item("详情", detailFragment));
        items.add(new FragmentPagerAdapter.Item("评论(" + modleFourBean.getGame_comment_count() + ")", CommentAllListFragment.newInstance(intentData)));
//        items.add(new FragmentPagerAdapter.Item("其他版本", GameDetialOthergameFragment.newInstance(modleFourBean.getGame_id())));
        FragmentPagerAdapter adapter = new FragmentPagerAdapter(getSupportFragmentManager(), items);

//        DetialPagerAdapter adapter=new DetialPagerAdapter(getSupportFragmentManager(),modleFourBean);
//        List<String> strings=new ArrayList<>();
//        strings.add("详情");
//        strings.add("评论(" + modleFourBean.getGame_comment_count() + ")");
//        strings.add("其他版本");
//        adapter.addDatas(strings);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0);
        viewPager.setOffscreenPageLimit(3);
        tabs.setViewPager(viewPager);
//        tabs.setupWithViewPager(viewPager);
        viewPager.setCurrentItem(0);
        toolbar.setTitle(modleFourBean.getGame_name());

        colltoobar.setExpandedTitleColor(Color.alpha(0));//设置还没收缩时状态下字体颜色
        colltoobar.setCollapsedTitleTextColor(Color.WHITE);//设置收缩后Toolbar上字体的颜色
//        handlerLoding.sendEmptyMessageDelayed(1, 500);
        hideLodingLayout();
    }


    void initView(GameInfoDetial modleFourBean) {
        tips.removeAllViews();
        for (GameTagInfoBean tagInfoBean : modleFourBean.getGame_tag_info()) {
//            View view= LayoutInflater.from(context).inflate(R.layout.)
            LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(this).inflate(
                    R.layout.search_label_tv, tips, false);
            TextView textView = linearLayout.findViewById(R.id.tipText);
//            TextView textView = new TextView(context);
            textView.setText(tagInfoBean.getName());
            textView.setPadding(getResources().getDimensionPixelOffset(R.dimen.wdp12), 0, getResources().getDimensionPixelOffset(R.dimen.wdp12), 0);
            textView.setBackgroundResource(R.drawable.game_detial_tip_back);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
            tips.addView(linearLayout);
        }

        try {
            detail_icon.setImageURI(Uri.parse(modleFourBean.getGame_ico()));
            List<GameTagInfoBean> gameTagInfoBeans=modleFourBean.getGame_tag_info();
            if (gameTagInfoBeans!=null){
                for (GameTagInfoBean bean:gameTagInfoBeans){
                    if (bean.getId().equals("25")){
                        Drawable drawable=getResources().getDrawable(R.mipmap.conner_tip);
                        detail_icon.getHierarchy().setOverlayImage(drawable);
                        break;
                    } else {
                        detail_icon.getHierarchy().setOverlayImage(null);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        appName.setText(modleFourBean.getGame_name());
        tv_autho.setText("上传者：" + modleFourBean.getGame_upload_author());
        if (StringUtils.isNotEmpty(modleFourBean.getGame_explain())) {
            versionInfo.setText(modleFourBean.getGame_explain());
            versionInfo.setVisibility(View.VISIBLE);
            line.setVisibility(View.VISIBLE);
        } else {
            versionInfo.setVisibility(View.GONE);
            line.setVisibility(View.GONE);
        }
        installButn.initData(gameId, modleFourBean);
        installButn.updateButn(modleFourBean.getTaskTable());
        if (modleFourBean.getGame_is_collect() == 1) {
            folowGame.setImageResource(R.mipmap.ic_folowgame_image);
            folowText.setText("已收藏");
        }
    }

    @Override
    public void onStart() {
        super.onStart();

    }



    @Override
    public void onBackPressed() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            overridePendingTransition(0, R.anim.slide_bottom_out);
            finish();
//            finishAfterTransition();
        } else {
            finish();
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.slide_bottom_out);
    }

    @OnClick({R.id.backImag, R.id.load_version, R.id.commentButn, R.id.shareButn, R.id.folowGameLayout})
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.backImag:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                    finishAfterTransition();

                    finish();
//                    ha.sendEmptyMessageDelayed(1, 300);
                } else {
                    finish();
                }
                break;
            case R.id.load_version:
                //tudo  上传游戏
                if (AccountUtil.getInstance().getUidNotToLogin(context) == 0 || modleFourBean==null) return;
                IntentUtil.getInstance().goShareWebActivity(context, MyApplication.cfgPlug.getValue_game_upload_url_v3()+"?gameId="+gameId+"&gameName="+modleFourBean.getGame_name());
                break;
            case R.id.commentButn:
                if (AccountUtil.getInstance().getUidNotToLogin(context) == 0) return;
                //tudo  去评论
                if (AccountUtil.getInstance().getUidNotToLogin(context) == 0) return;
                Intent intent = new Intent(context, CommentCreatActivity.class);
                if (detailFragment!=null) {
                    selfComment = detailFragment.getSelfComment();
                }
                if (selfComment!=null) {
                    intent.putExtra("isEdit", true);
                    intent.putExtra("commentId", selfComment.getId());
                    intent.putExtra("phoneModel", selfComment.getMobile_phone_model());
                    intent.putExtra("commentContent", selfComment.getContent());
                }
                intent.putExtra("gameId", gameId);
                startActivity(intent);
                break;
            case R.id.shareButn:
                if (modleFourBean != null) {
                    if (AccountUtil.getInstance().getUidNotToLogin(context) == 0) return;
                    JumpBaseBean baseBean = modleFourBean.getGame_share_ad();
                    IntentUtil.getInstance().intentTo(context, baseBean);
                }
//                IntentUtil.getInstance().goShareWebActivity(context, MyApplication.cfgPlug.getValue_share_invite_game_url() + gameId);
                break;
            case R.id.folowGameLayout:
                folowgame(gameId);
                break;
        }
    }

    private CommentBaseBean selfComment = null;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {
        GameListBaseBean bean = modleFourBean;
        if (bean == null) return;
        if (bean.getGame_id().equals(downloadEvent.getGameId())) {
            DownLoadTaskTable table = bean.getTaskTable();
            if (table == null) {
                table = bean.getDownloadTaskTableSimple();
            }
            table.setDownStatus(downloadEvent.status);
            if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                table.setDownprogress(downloadEvent.getProgress());
            }
            installButn.updateButn(table);
        }
        super.onEventMainThread(downloadEvent);
    }
}
